<template>
    <view class="container">
        <!-- Custom Header (Non-Homepage, Logged-in Mourning Variant) -->
        <custom-header :isHomepage="false" headerVariant="mourning"></custom-header>
        <view class="main-content">

            <!-- 分类 -->
            <view class="offering-category-bar top-bar">
                <view class="category-item" v-for="(category, index) in jidianCate" :key="category.id"
                    :class="{ active: selectedJidianCate === category.id }" @click="selectJidianCate(category)">
                    {{ category.name }}
                </view>
            </view>

            <!-- Content Card/Area -->
            <view class="content-card">
                <!-- Section Title -->
                <view class="section-title-area">
                    <text class="section-title">给{{ muDetail.is_double == 1 ? muDetail.name + '、' + muDetail.name2 : muDetail.name }}献{{ selectedJidianCateText }}</text>
                </view>
                <!-- Offering Grid -->
                <view style="width: 100%;display: flex;align-items: center;justify-content: center;"
                    v-if="jidianList.length === 0">
                    <van-empty description="暂无祭品" />
                </view>
                <view class="options-grid">
                    <view class="option-item offering-item" v-for="(offering, index) in jidianList" :key="offering.id"
                        :class="{ selected: selectedOfferingId === offering.id }" @click="selectOffering(offering)">
                        <image class="option-image" :src="offering.file_url" mode="aspectFit" v-if="offering.file_type != 2"></image>
                        <image class="option-image" src="/static/audio_img.jpg" mode="aspectFit" v-if="offering.file_type == 2"></image>
                        <!-- Use aspectFit for offerings -->
                        <view class="option-text-area">
                            <text class="option-label">{{ offering.name }}</text>
                        </view>
                        <!-- Upgrade Special Tag -->
                        <view class="upgrade-tag" v-if="offering.isUpgradeSpecial">升级馆专用</view>
                        <!-- Radio button style indication -->
                        <view class="radio-button">
                            <view class="radio-dot" v-if="selectedOfferingId === offering.id"></view>
                        </view>
                    </view>
                </view>
                <view class="guestbook-form">
                    <text class="form-label">签名留言:</text>
                    <view class="input-wrapper signature-input-wrapper">
                        <input 
                            type="text" 
                            placeholder="请输入签名" 
                            v-model="signatureInput" 
                            class="signature-input"
                        />
                    </view>
                    <view class="textarea-wrapper">
                        <textarea class="form-textarea" auto-height placeholder="留言内容"
                            v-model="messageContent"></textarea>
                    </view>
                    <!-- <text class="word-count">{{ messageContent.length }}/300字以内</text> -->
                </view>

                <button class="submit-button" @click="handleSubmitMessage">提交</button>
                <button class="submit-button-back" @click="handleReturn">返回</button>

                <view class="notes-area">
                    <text class="note-text">纪念净地，祭奠留言请保持肃穆!</text>
                    <text class="note-text warning">公安网警提醒: 切勿发布违法信息!</text>
                </view>
            </view>
            <!-- End Content Card -->
            <Footer></Footer>
        </view>

    </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, onMounted, computed } from 'vue';
import CustomHeader from '@/components/header/index.vue'; // Adjust path as needed
// import { onLoad } from '@dcloudio/uni-app'; // If getting memorial ID from options
import { apiMuDetail } from '@/api/graveyard'
import { apiMuJidianCate, apiMuJidianList, apiMuAddLeaveNote } from '@/api/leaveNote'
import Footer from '@/components/footer/index.vue'
import { find } from 'lodash';
const allOfferings = ref([]);

const messageContent = ref('')
const signatureInput = ref('') // 签名输入框数据
const tabIndex = ref()
// --- Page Specific Event Handlers ---
const handleReturn = () => {
    console.log('Return link clicked');
    uni.navigateBack(); // Assuming this page is accessed from memorial detail or management
};


const handleSubmitMessage = async () => {
    console.log('Submit Message button clicked');
    if (!selectedOfferingId.value) {
        uni.showToast({ title: '请选择献祭品', icon: 'none' });
        return;
    }
    if (!messageContent.value.trim()) {
        uni.showToast({ title: '请填写留言内容', icon: 'none' });
        return;
    }
    if (!signatureInput.value.trim()) {
        uni.showToast({ title: '请填写签名', icon: 'none' });
        return;
    }
    let res = await apiMuAddLeaveNote({
        mu_id: mu_id.value,
        jidian_id: selectedOfferingId.value,
        content: messageContent.value,
        sign_name: signatureInput.value
    })
    if(res.code === 1){
        uni.showToast({ title: '提交成功', icon: 'success' }); 
        selectedOfferingId.value = ''
        messageContent.value = ''
        signatureInput.value = ''
		uni.navigateBack({
			delta: 1
		})
    }
    // const selectedOffering = allOfferings.value.find(o => o.id === selectedOfferingId.value);
    // console.log('Submitting:');
    // console.log('Memorial ID:', 'Need to get memorial ID from params'); // Need actual memorial ID
    // console.log('Selected Offering:', selectedOffering);
    // console.log('Signature:', signatureInput.value || userInfo.value?.nickname || '用户'); // 使用输入的签名或默认昵称
    // console.log('Message Content:', messageContent.value);

    // Implement logic to send the offering and guestbook message to the backend API
    // After successful submission, clear the form and show success message
    // messageContent.value = '';
    // signatureInput.value = '';
    // selectedOfferingId.value = null;
};

// 获取墓地详情
const muDetail = ref({})
const mu_id = ref('')

const getMemorialDetail = async () => {
    const res = await apiMuDetail({
        id: mu_id.value
    })
    if (res.code === 1) {
        muDetail.value = res.data
    }
}

// 获取祭品分类
const jidianCate = ref([])
const selectedJidianCate = ref()
const selectedJidianCateText = ref('')
const getJidianCate = async () => {
    const res = await apiMuJidianCate()
    if (res.code === 1) {
        jidianCate.value = res.data
		if(tabIndex.value){
			let obj = res.data.find((item)=>item.name == tabIndex.value)
			selectedJidianCate.value = obj.id
			selectedJidianCateText.value = obj.name
		}else{
			selectedJidianCate.value = res.data[0].id
			selectedJidianCateText.value = res.data[0].name
		}
        getJidianList()
    }
}

// 获取祭品列表
const jidianList = ref([])
// 祭品选择id
const selectedOfferingId = ref('')
const getJidianList = async () => {
    const res = await apiMuJidianList({ cid: selectedJidianCate.value })
    if (res.code === 1) {
        jidianList.value = res.data
    }
}

// 祭品分类点击事件
const selectJidianCate = (cate) => {
    selectedJidianCate.value = cate.id
	selectedJidianCateText.value = cate.name
    getJidianList()
}
// 祭品点击事件
const selectOffering = (offering) => {
    selectedOfferingId.value = offering.id
}

onLoad((options) => {
	console.log(options)
    if (options.mu_id) {
        mu_id.value = options.mu_id
    }
	if (mu_id.value) {
	    getMemorialDetail()
	}
	if(options.tabIndex){
		tabIndex.value = options.tabIndex
	}
	getJidianCate()
})
onMounted(() => {
    
});
</script>

<style scoped>
/* Scoped styles for this page */
/* Reusing common styles from previous pages */
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #f5f5f5;
    /* Match background color */
    padding-bottom: 40rpx;
    /* Add some padding at the bottom */
    box-sizing: border-box;
    /* Include padding in height calculation */
}

/* Custom Header - Styles are in CustomHeader.vue */
/* Need padding on main content to clear fixed header */

/* Standard Banner (Optional, based on site structure) */
/* Uncomment and adjust if a full banner image is expected here */
/* .banner { ... } .banner-bg { ... } .banner-overlay { ... } ... */


/* Main Content Area */
.main-content {
    /* No specific background or padding here, handled by individual sections/card */
    display: flex;
    flex-direction: column;
    align-items: center;
    /* Center sections horizontally */
    padding: 0 20rpx;
    /* Side padding for the whole content block */
}

/* Offering Category Bar (Top and Bottom) */
.offering-category-bar {
    width: 100%;
    /* Take full width */
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: flex-start;
    gap: 20rpx;
    /* display: grid; */
    /* grid-template-columns: repeat(6, 1fr); */
    /* grid-gap: 10rpx; */
    background-color: #fff;
    /* White background */
    border-bottom: 1rpx solid #eee;
    /* Separator */
    padding: 20rpx 0;
    /* Vertical padding */
    box-sizing: border-box;
}

.offering-category-bar.top-bar {
    margin-top: 88rpx;
    /* Push down by header height */
}

.offering-category-bar.bottom-bar {
    margin-top: 30rpx;
    /* Space above bottom bar */
}


.category-item {
    min-width: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #333;
    padding: 5rpx 10rpx;
    /* Inner padding */
    /* Optional: add border or background for active state */
    position: relative;
    /* Needed for underline */
}

.category-item.active {
    color: #ff9800;
    /* Orange color for active */
    font-weight: bold;
}

/* Add underline for active category */
.category-item.active::after {
    content: '';
    position: absolute;
    bottom: -15rpx;
    /* Adjust position below text */
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    /* Underline width */
    height: 4rpx;
    /* Underline thickness */
    background-color: #ff9800;
    /* Orange underline */
}


/* Content Card */
.content-card {
    background-color: #fff;
    /* White background */
    width: 100%;
    /* Take full width within main-content padding */
    padding: 30rpx 20rpx;
    /* Inner padding */
    border-radius: 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    /* Subtle shadow */
    margin-top: 20rpx;
    /* Space below top category bar */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    /* Content stacked vertically */
}

/* Section Title Area */
.section-title-area {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    /* Space below title area */
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.return-link {
    font-size: 26rpx;
    color: #666;
    /* Gray color */
    text-decoration: none;
    /* Remove underline */
}


/* Sub-category Bar (within card, conditional) */
.offering-category-bar.sub-bar {
    padding: 10rpx 0;
    /* Smaller vertical padding */
    margin-bottom: 20rpx;
    /* Space below sub-bar */
    /* No border-bottom here, handled by grid margin */
}

.offering-category-bar.sub-bar .category-item {
    font-size: 26rpx;
    /* Smaller font */
    padding: 3rpx 8rpx;
}

.offering-category-bar.sub-bar .category-item.active::after {
    bottom: -10rpx;
    /* Adjust underline position */
    height: 3rpx;
    /* Thinner underline */
}


/* Offering Grid - Similar to cemetery options grid */
.options-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
}

.option-item.offering-item {
    flex: 1;
    /* Base style for grid items */
    /* width: calc((100% - 60rpx) / 4);  */
    /* Calculate width for 4 per row */
    height: 220rpx;
    /* Adjust height for offering items */
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    margin: 0 10rpx 20rpx 10rpx;
    /* Margin around items */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding: 10rpx;
    position: relative;
    background-color: #fff;
    /* Explicit white background */
}

.option-item.offering-item.selected {
    border-color: #ff9800;
    background-color: #fff7e6;
}

.option-image {
    width: 100%;
    flex-grow: 1;
    margin-bottom: 5rpx;
    object-fit: contain;
    /* Ensure image fits within bounds */
    border-radius: 5rpx;
}

.option-text-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 22rpx;
    /* Smaller font for option labels */
    color: #333;
    text-align: center;
    width: 100%;
    flex-shrink: 0;
}

.option-label {
    /* No specific style */
    white-space: nowrap;
    /* Prevent wrapping */
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
    /* Prevent overflow issues */
}

.option-status {
    color: #999;
    font-size: 20rpx;
}

/* Upgrade Special Tag */
.upgrade-tag {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #ffb6c1;
    /* Light pink background */
    color: #333;
    /* Text color */
    font-size: 18rpx;
    /* Very small font */
    padding: 2rpx 8rpx;
    /* Padding */
    border-top-left-radius: 8rpx;
    /* Match item border radius */
    border-bottom-right-radius: 8rpx;
    z-index: 5;
    /* Ensure it's above the image */
}


/* Radio Button Style (within offering grid) */
.radio-button {
    position: absolute;
    top: 10rpx;
    right: 10rpx;
    /* Position on the right */
    width: 30rpx;
    height: 30rpx;
    border: 1rpx solid #999;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    z-index: 5;
    /* Ensure it's above the image */
}

.option-item.selected .radio-button {
    border-color: #ff9800;
}

.radio-dot {
    width: 18rpx;
    height: 18rpx;
    background-color: #ff9800;
    border-radius: 50%;
}


/* Pagination Section */
.pagination-section {
    display: flex;
    justify-content: flex-end;
    /* Align to the right */
    align-items: center;
    width: 100%;
    margin-top: 20rpx;
    /* Space above pagination */
    margin-bottom: 30rpx;
    /* Space below pagination */
    font-size: 26rpx;
    color: #666;
}

.pagination-text-area {
    display: flex;
    align-items: center;
    margin-right: 10rpx;
    /* Space before picker */
}

.pagination-button {
    /* Style for "第一页", "上一页", etc. text links */
    margin: 0 8rpx;
    /* Space between text links */
    color: #666;
    /* Gray color */
    text-decoration: none;
    /* Remove underline */
}

.jump-label {
    margin-left: 10rpx;
    /* Space before "跳到" */
    margin-right: 5rpx;
    /* Space after "跳到" */
}

/* Page Picker Styled as a Button/Input (within pagination) */
.page-picker-wrapper {
    position: relative;
    height: 50rpx;
    /* Smaller height */
    line-height: 50rpx;
    font-size: 26rpx;
    color: #333;
    background-color: #fff;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    padding: 0 20rpx 0 10rpx;
    /* Padding for text and arrow */
    display: flex;
    align-items: center;
    min-width: 100rpx;
    /* Minimum width */
    text-align: center;
    /* Center text */
}

.page-picker-text {
    flex: 1;
    text-align: center;
}

.page-picker-wrapper .picker-arrow-icon {
    position: static;
    /* Change position from absolute */
    margin-left: 5rpx;
    /* Space from text */
    font-size: 20rpx;
    /* Smaller arrow */
    color: #666;
}


/* Guestbook/Signature Form */
.guestbook-form {
    width: 100%;
    /* Take full width */
    margin-bottom: 30rpx;
    /* Space below form */
}

.form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    display: block;
}

/* Reusing input and textarea styles from previous forms */
.input-wrapper.signature-input-wrapper {
    /* border: 1rpx solid #ddd; */
    border-radius: 5rpx;
    /* padding: 0 20rpx; */
    height: 80rpx;
    margin-bottom: 20rpx;
    /* Space below signature input */
}

.signature-input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    background-color: #fff;
    box-sizing: border-box;
}

.signature-input:focus {
    border-color: #007aff;
    outline: none;
}

.form-input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
    color: #333;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 0;
    background-color: transparent;
}

.textarea-wrapper {
    border: 1rpx solid #ddd;
    border-radius: 5rpx;
    padding: 20rpx;
    margin-bottom: 10rpx;
    /* Space below textarea */
}

.form-textarea {
    width: 100%;
    font-size: 28rpx;
    color: #333;
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    background-color: transparent;
    line-height: 1.5;
}

.word-count {
    display: block;
    /* Below textarea */
    text-align: right;
    /* Align to the right */
    font-size: 24rpx;
    color: #999;
}

/* Submit Button */
.submit-button {
    /* Plum/Maroon color button */
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    color: #fff;
    background-color: #8b008b;
    /* Adjust color to match image (plum/maroon) */
    border: none;
    border-radius: 8rpx;
    text-align: center;
    margin-top: 30rpx;
    /* Space above button */
    margin-bottom: 20rpx;
    /* Space below button */
    display: flex;
    align-items: center;
    justify-content: center;
}
.submit-button-back {
    /* Plum/Maroon color button */
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    color: #000;
    border: 1px solid #8b008b;
    /* Adjust color to match image (plum/maroon) */
    border-radius: 8rpx;
    text-align: center;
    margin-top: 30rpx;
    /* Space above button */
    margin-bottom: 20rpx;
    /* Space below button */
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Notes/Warning Area */
.notes-area {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
    /* Space below notes */
    padding: 15rpx;
    /* Inner padding */
    background-color: #ffc0cb;
    /* Light pink background */
    border-radius: 8rpx;
    box-sizing: border-box;
}

.note-text {
    display: block;
    /* Each note on a new line */
    font-size: 24rpx;
    color: #333;
    /* Dark gray text */
    text-align: center;
    margin-bottom: 5rpx;
}

.note-text.warning {
    color: red;
    /* Red color for warning */
    font-weight: bold;
}

.notes-area .note-text:last-child {
    margin-bottom: 0;
}


/* QR Codes Section - Copied from previous pages */
.qr-codes-section {
    display: flex;
    justify-content: space-around;
    padding: 40rpx 0;
    margin-top: 30rpx;
    /* Space above section */
    margin-left: 20rpx;
    /* Side margins */
    margin-right: 20rpx;
}

.qr-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.qr-image {
    width: 200rpx;
    height: 200rpx;
    /* Need actual images */
    background-color: #eee;
    /* Placeholder background */
}

.qr-label {
    font-size: 26rpx;
    color: #555;
    margin-top: 10rpx;
}

/* Footer Styles - Copied from previous pages */
.footer {
    margin-top: 40rpx;
    padding: 40rpx 20rpx;
    background-color: #f0f0f0;
    /* Light gray background */
    text-align: center;
    margin-top: auto;
    /* Push footer to the bottom */
    box-sizing: border-box;
}

.footer-links {
    font-size: 26rpx;
    color: #555;
    margin-bottom: 20rpx;
}

.footer-links text {
    margin: 0 10rpx;
}

.footer-copyright {
    font-size: 22rpx;
    color: #888;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.footer-copyright text {
    margin-bottom: 5rpx;
}

/* Padding to clear the fixed header */
/* This style is crucial for pages using the fixed custom header */
.page-content-wrapper {
    padding-top: 88rpx;
    /* Height of the fixed header */
    flex: 1;
    /* Allow content to take space */
    display: flex;
    flex-direction: column;
}
</style>